package com.bb.blog.code.mybatis.mapper;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapperXScanRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoader {

    private static String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
        return importingClassMetadata.getClassName() + "#" + MapperXScanRegistrar.class.getSimpleName() + "#" + index;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes mapperXScanAttrs = AnnotationAttributes.fromMap(
            importingClassMetadata.getAnnotationAttributes(MapperXScan.class.getName()));
        if (mapperXScanAttrs != null) {
            registerBeanDefinitions(mapperXScanAttrs, registry, generateBaseBeanName(importingClassMetadata, 0));
        }
    }

    public void registerBeanDefinitions(AnnotationAttributes annoAttr,
                                        BeanDefinitionRegistry registry,
                                        String beanName) {

        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperXBeanDefinitionRegistryPostProcessor.class);
        List<String> basePackages =
            new ArrayList<>(
                Arrays.stream(
                    annoAttr.getStringArray("scanPackages")
                ).filter(StringUtils::hasText).collect(Collectors.toSet())
            );
        builder.addPropertyValue("scanPackages", StringUtils.collectionToCommaDelimitedString(basePackages));

//        builder.addPropertyValue("sqlSessionXFactory", "sqlSessionXFactory");
        registry.registerBeanDefinition(beanName, builder.getBeanDefinition());


    }

    @Override
    public Resource getResource(String s) {
        return null;
    }

    @Override
    public ClassLoader getClassLoader() {
        return null;
    }

}
